package mop.controller;

import java.util.LinkedList;
import java.util.List;

import mop.exception.IllegalIdException;
import mop.model.World;
import mop.model.project.Project;
import mop.model.project.ProjectInterface;
import mop.model.task.Task;
import mop.model.task.TaskInterface;

/**
 * Controller for assigning tasks to projects.
 * (use case 7)
 * 
 * @note	The implementation of this use case shows a list of ALL tasks (super.getAllTasks()).
 * 			If a project is assigned to a task that was already assigned to a project,
 * 			then that "assignment" is changed to the newly selected project.
 * 
 * @author	MOP Team 7
 */
public class AssignTaskToProjectController 
	extends UseCaseController
{	
	/**
	 * Constructor.
	 * 
	 * @param 	system
	 * 			The system object.
	 * @post	System reference is set
	 * 			| this.system == system
	 */
	public AssignTaskToProjectController(World system)
	{
		super(system);
	}
	
	/**
	 * Returns a list of all tasks as interfaces.
	 * 
	 * @return	A list of task interfaces.
	 */
	public List<TaskInterface> getTaskList()
	{
		return super.getAllTasks();
	}
	
	/**
	 * Returns a list of tasks (as interfaces) that are assigned to a given project.
	 * 
	 * @param 	project
	 * 			The interface for the project.
	 * @return	A list of tasks (as interfaces) that are assigned to a given project.
	 */
	public List<TaskInterface> getAssignedTasks(ProjectInterface project)
	{
		LinkedList<TaskInterface> assignedTasks = new LinkedList<TaskInterface>();
		
		for ( TaskInterface t : super.getAllTasks() )
		{
			if ( t.getProject().equals(project) )
				assignedTasks.add(t);
		}
		
		return assignedTasks;
	}
	
	/**
	 * @see UseCaseController#getAllProjects()
	 */
	public List<ProjectInterface> getProjectList()
	{
		return super.getAllProjects();
	}
	
	/**
	 * Assigns a task to a project (and replaces old assignment if necessary).
	 * 
	 * @param 	task
	 * 			The description (String) of a Task.
	 * @param 	project
	 * 			The description (String) of a Project.
	 * @effect	Sets the project assignment in the given task.
	 * 			| task.setProject(project)
	 * @effect	Adds the task to the project.
	 * 			| project.addTask(task)
	 * @throws 	IllegalIdException
	 * 			Thrown when the task or project description is invalid, or does not exist.
	 */
	public void assignTaskToProject(String task, String project) 
		throws IllegalIdException
	{
		// find corresponding task and project
		Task t = super.getTask(task);
		Project p = super.getWorld().getProjectDataBase().find(project);
		
		// set project assignment in the task
		// (replaces old assignment if necessary)
		t.setProject(p);
		
		// add task to project
		p.addTask(t);
	}
	
	
	/***************************************************************************
	 * 								Visit
	 ***************************************************************************/
	
	/**
	 * Make a CallBack to the visitor
	 * @param v the visitor
	 */
	public void visit(ControllerVisitor v)
	{
		v.action(this);
	}
}